<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- 提示区域 -->
            <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
            </el-alert>
            <!-- 步骤条区域 -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <!-- tab栏区域 -->
            <el-form :model="addForm" :rules="addFules" ref="addFormRef" label-width="100px">
            <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="productName">
                        <el-input v-model="addForm.productName"></el-input>
                    </el-form-item>
                    <el-form-item label="商品标题" prop="productTitle">
                        <el-input v-model="addForm.productTitle"></el-input>
                    </el-form-item>
                    <el-form-item label="商品描述" prop="productDescribe">
                        <el-input v-model="addForm.productDescribe"></el-input>
                    </el-form-item>
                    <el-form-item label="市场价" prop="marketPrice">
                        <el-input v-model="addForm.marketPrice" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="是否开启促销">
                        <el-checkbox v-model="checked"></el-checkbox>
                        <el-alert style="display: inline; margin-left: 10px;" title="(注意：开启促销需要输入促销价，商品出售时将按照促销价售卖，否则按市场价出售。)" type="warning" effect="dark" :closable="false" show-icon>
                        </el-alert>
                    </el-form-item>
                    <el-form-item label="促销价" prop="promotionPrice" v-show="checked">
                        <el-input v-model="addForm.promotionPrice" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="库存" prop="inventory">
                        <el-input v-model="addForm.inventory" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品类型" prop="productType">
                        <el-select v-model="addForm.productType" placeholder="请选择" value-key="productTypeId">
                            <el-option v-for="productType in productTypeList" :key="productType.productTypeId"
                            :label="productType.productTypeName" :value="productType">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="1">
                    <!-- action 表示图片上传的后台API地址 -->
                    <el-upload :action="uploadURL" 
                        name="multipartFile" :data="uploadData"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove" list-type="picture-card"
                        :on-success="handleSuccess" :limit="5">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                        <div slot="tip" class="el-upload__tip" style="font-size: 14px;">上传规则：<br>1.最多上传5张图片；<br>
                            2.第一张图片默认为商品的主图，其余图片为副图，若只上传一张图片，则该商品没有副图。
                        </div>
                    </el-upload>
                    <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
                </el-tab-pane>
                <!-- <el-tab-pane label="角色管理" name="2">角色管理</el-tab-pane> -->
            </el-tabs>
            </el-form>
        </el-card>

        <!-- 图片预览 -->
        <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
            <img :src="previewPath" alt="">
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            activeIndex: '0',
            //添加商品的表单数据对象
            addForm: {
                productName: '',
                productTitle: '',
                productDescribe: '',
                marketPrice: '',
                promotionPrice: '',
                inventory: '',
                //商品所属的类型
                productType: {
                    productTypeId: '',
                    productName: ''
                },
                //图片的数组
                pics: []
            },
            addFules: {
                productName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                productTitle: [
                    { required: true, message: '请输入商品标题', trigger: 'blur' }
                ],
                productDescribe: [
                    { required: true, message: '请输入商品描述', trigger: 'blur' }
                ],
                marketPrice: [
                    { required: true, message: '请输入市场价', trigger: 'blur' }
                ],
                // promotionPrice: [
                //     { required: true, message: '请输入促销价', trigger: 'blur' }
                // ],
                inventory: [
                    { required: true, message: '请输入库存数量', trigger: 'blur' }
                ],
                productType: [
                    { required: true, message: '请选择商品类型', trigger: 'blur' }
                ]
            },
            //商品类型列表
            productTypeList: [],
            // productTypeProp: {
            //     label: 'productTypeName',
            //     value: 'productTypeId'
            // }
            //上传图片的地址
            // uploadURL: this.$target+'http://localhost:8081/flower-store/upload',
            uploadURL: this.$target+'upload',
            previewPath: '',
            //预览图片对话框的显示和隐藏
            previewVisible: false,
            //控制开启促销的开关
            checked: false,
            //上传时的参数
            uploadData: {
                dir: 'product'  //上传目录
            }
        }
    },
    created() {
        this.getProductTypeList();
    },
    watch: {
        //监听促销开关
        checked: function(val){
            //如果取消商品的促销，则清空促销价格
            if(!val) {
                this.addForm.promotionPrice = ''
            }
        }
    },
    methods: {
        //获取所有商品分类
        getProductTypeList() {
            this.$axios
            .get('/productType')
            .then(res => {
                const data = res.data;
                if(data.code !== '001') return this.$notifyError("商品类型数据获取失败");
                this.productTypeList = data.list;
            })
            .catch(err => {
                console.log(err);
            });
        },
        beforeTabLeave(activeName, oldActiveName){
            // console.log(activeName)
            // console.log(oldActiveName)
            let result;
            this.$refs.addFormRef.validate(valid => {
                result = valid;
            })
            if(!result){
                this.$notifyError("请填写必要的表单数据")
                return false;
            }
            if(oldActiveName === '0' && this.addForm.productType.productTypeId === ''){
                this.$notifyError('请选择商品分类');
                return false;
            }
        },
        //处理图片预览效果
        handlePreview(file) {
            //待完善
            console.log(file);
            const localhost = this.$axios.defaults.baseURL;
            this.previewPath = localhost + "/static" + file.response.relativePath;
            this.previewVisible = true;
        },
        //处理移除图片的事件
        handleRemove(file) {
            // console.log(file);
            //1.获取将要删除的图片的临时路径
            const filePath = file.response.relativePath;
            //2.从pics数组中，找到这个图片对应的索引值
            const i = this.addForm.pics.findIndex(x => x.pic === filePath);

            //3.调用数组的splice方法，把图片信息对象，从pics数组中移除
            this.addForm.pics.splice(i, 1);
            console.log(this.addForm.pics);
        },
        //监听图片上传成功的事件
        handleSuccess(response) {
            //1.拼接得到一个图片信息对象
            const picInfo = { pic: response.url };
            //2.将图片信息对象，push到pics数组中
            this.addForm.pics.push(picInfo);
            console.log(this.addForm.pics)
        },
        //添加商品
        add() {
            this.$refs.addFormRef.validate(valid => {
                if(!valid) return this.$notifyError("请填写必要的表单数据");
                if(this.addForm.pics.length === 0) return this.$notifyError("请上传商品的图片");
                console.log(this.addForm);
                //提交数据
                this.$axios
                .post('/product', this.addForm)
                .then(res => {
                    const data = res.data;
                    if(data.code !== '001') return this.$notifyError(data.msg);
                    this.$notifySucceed(data.msg);
                    //跳转商品页面
                    this.$router.push('/product');
                })
                .catch(err => {
                    console.log(err);
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
.btnAdd {
    margin-top: 15px;
}
</style>